package org.farm2.tools.db.commons;

import java.lang.reflect.Field;
import java.util.UUID;

public class FarmUUID {

    /**生成32位的UUID
     * @return
     */
    public static String getUUID32() {
        String uId = UUID.randomUUID().toString().replaceAll("-", "");
        return uId;
    }

    /**将32位的uuid填充到对象obj中
     * @param object 要填充的对象
     * @param fieldName 要填充uuid的字段名称
     * @param <T>  对象类型
     * @return 返回填充好数据的对象
     */
    public static <T> T to(T object, String fieldName) {
        if (object == null || fieldName == null || fieldName.isEmpty()) {
            return object;
        }
        try {

            Field[] fields = object.getClass().getDeclaredFields();

            String lowerCaseFieldName = fieldName.toLowerCase();
            for (Field field : fields) {

                if (field.getName().toLowerCase().equals(lowerCaseFieldName)) {

                    field.setAccessible(true);

                    if (field.getType() == String.class) {

                        String fieldValue = (String) field.get(object);

                        if (fieldValue == null || fieldValue.trim().isEmpty()) {
                            field.set(object, getUUID32());
                        }
                    }
                    break; // 找到匹配的字段后退出循环
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return object;
    }
}
